package com.felix.algorithms.sort;

import java.util.LinkedList;

/**
 * MergeSort
 *
 * @author xuejinhua
 * @date 2019/1/17 11:29
 */
public class MergeSort {

    /**
     * 交换数组元素
     *
     * @param x
     * @param a
     * @param b
     */
    public static void swap(int[] x, int a, int b) {
        int t = x[a];
        x[a] = x[b];
        x[b] = t;
    }


    public static void merge(int[] src, int[] dest, int low, int high) { //left,right均为数字元素下标
        int length = high - low;
        if (length < 7) {
            for (int i = low; i < high; i++) {
                for (int j = i; j > low && dest[j - 1] > dest[j]; j--) {
                    swap(dest, j, j - 1);
                }
            }
            return;
        }
        int mid = (low + high) >>> 1;
        merge(dest, src, low, mid);
        merge(dest, src, mid, high);
        if (src[mid - 1] <= src[mid]) {
            System.arraycopy(src, low, dest, low, length);
            return;
        }
        for (int p = low, q = mid, i = low; i < high; i++) {
            if (q >= high || p < mid && src[p] < src[q]) {
                dest[i] = src[p++];
            } else {
                dest[i] = src[q++];
            }
        }
        new LinkedList<Integer>();
    }

    public static void printArray(int arr[]) {
        for (int k = 0; k < arr.length; k++) {
            System.out.print(arr[k] + "\t");
        }
    }

    public static int[] getArray() {
//      int[] data={4,2,3,1};
        int[] data = {543, 23, 45, 65, 76, 1, 456, 7, 77, 88, 3, 9};
        return data;
    }

    public static void main(String args[]) {
        int[] a = getArray();
        int[] dest = new int[a.length];
        System.out.print("数组排序前：");
        printArray(a);
        System.out.print("\n");
        merge(a, dest, 0, a.length);
        System.out.print("归并排序后：");
        printArray(dest);
    }
}
